/**
 * @param {*} options 
 */
var DataHandler = function(options){
    var t = this;
    t.options = $.parseJSON(JSON.stringify(options));
    t.$dom = $(options.container);
    t.$dom.html(DataHandler.showChartTpl.render({
    	labelAll : cmp.i18n("report.result.common.all"),
    	labelItems : cmp.i18n("report.result.common.show.items"),
    	labelOk : cmp.i18n("report.common.ok"),
    	labelReset : cmp.i18n("report.common.reset")
    }));
    
    t._init_event_();
    t._load_({
    	"userConditions":t.options.userConditions
    });
}
/**
 * 重新加载
 */
DataHandler.prototype.reload = function(userConditions){
	var t = this;
	t.options.userConditions = userConditions
	t._load_({
		"userConditions":t.options.userConditions
    });
}
/**
 * 加载并渲染数据
 */
DataHandler.prototype._load_=function(params){
	var t = this;
	var options = t.options;
	params.designId = options.designId;
	rptApi.getStatsLineResult({},params,{
		success:function(rs){
			cmp.dialog.loading(false);
			var isEmpty = (undefined == rs || undefined ==  rs.data) || function isEmptyObject(data){   
				for (var key in data){
					return false;
				}　　
				return true;
			}(rs.data);
			if(isEmpty){
				t.$dom.html("<div class='no-data-text'>"+cmp.i18n("report.common.nodata")+"</div>");
				DataHandler.alert(cmp.i18n("report.common.nodata"));
				return;
			}
			if(!rs.success){
				DataHandler.alert(rs.msg);
				return;
			}
			
			t.$dom.html(DataHandler.showChartTpl.render({
		    	labelAll : cmp.i18n("report.result.common.all"),
		    	labelItems : cmp.i18n("report.result.common.show.items"),
		    	labelOk : cmp.i18n("report.common.ok"),
		    	labelReset : cmp.i18n("report.common.reset")
		    }));
			var data = rs.data;
			var rowHeaders = [], statsFields = [], colHeader , fields = rs.fields , colData = rs.colData ;
			for(var i = 0, len1 = fields.length; i < len1; i++){
				var field = fields[i];
				if('H' == field.type){
					rowHeaders.push(field);
				}else if('S' == field.type){
					statsFields.push(field);
				}else if('C' == field.type){
					colHeader = field;
				}
			}
			t._data_ = data ,t._colData_ = colData, t._rowHeaders_ = rowHeaders ,t._statsFields_ = statsFields , t._colHeader_ = colHeader;
			
			//交叉项在前 统计项在后
			if(undefined != colHeader){
				t.$dom.find(".st-ct .op-ct .cross-set").html( DataHandler.opCrossTpl.render({colData:colData}));
	        }
			var showFields = [];
			if(statsFields.length < 10){
				showFields = statsFields;
			}else{
				showFields = statsFields.slice(0,10);
			}
			t._showFields_ = showFields;
			t.$dom.find(".st-ct .op-ct .show-items").html(DataHandler.statsItemsTpl.render({statsFields:statsFields}));
			t.showContentItems();
		},
		error:function(error){
			cmp.dialog.loading(false);
			var cmpHandled = cmp.errorHandler(error);
			if (!cmpHandled) {
				if (error.message) {
					DataHandler.alert(error.message);
				} else {
					DataHandler.alert(cmp.toJSON(error));
				}
			}
		}
	});
}
/**
 * 显示内容
 */
DataHandler.prototype.showContentItems = function(){
	var t = this;
	var rowHeaders = t._rowHeaders_ , statsFields = t._statsFields_, colHeader = t._colHeader_ , data = t._data_, colData = t._colData_ ;
	
	var crossIndex = t.$dom.find(".st-ct .op-ct .cross-st").val() || 0;
	var chartData = data[crossIndex] || [];
	
	var showFields = t._showFields_;
	var xAxisData = [],series = [] ,maxVal = 0;
	for(var i = 0, len1 = showFields.length; i < len1; i++){
    	var statsField = showFields[i];
    	series[i] = {name:statsField.fieldKey,type:'line',data:[]};
    }
	for(var i = 0, len1 = chartData.length; i < len1; i++){
		var rowData = chartData[i];
		var name;
		for (var j = 0, len2 = rowHeaders.length; j < len2; j++) {
			var field = rowHeaders[j] , cellData = rowData[field.cellKey];
			var display = (cellData.d == null ) ? "" : cellData.d;
			name = (j == 0) ? display : (name + '/' + display);
		}
		xAxisData[i] = name;
		for(var j = 0, len2 = showFields.length; j < len2; j++){
			var field = showFields[j] , cellData = rowData[field.cellKey];
        	var value = (null == cellData.v) ? 0 : Math.floor(cellData.v);
        	series[j].data[i] = value;
        	if(Math.floor(value) > maxVal){
        		maxVal = value;
        	}
        }
	}
	var defaultColors = DataHandler.defaultColors;
	//列表
	var listHtml = DataHandler.listCtTpl.render({showFields:showFields,defaultColors:defaultColors});
	t.$dom.find(".list-ct").html(listHtml);
	
	var listData = [];
	for(var i = 0, len1 = chartData.length; i < len1; i++){
		var rowData = chartData[i];
		var name;
		for (var j = 0, len2 = rowHeaders.length; j < len2; j++) {
			var field = rowHeaders[j] , cellData = rowData[field.cellKey];
			var display = (cellData.d == null ) ? "" : cellData.d;
			name = (j == 0) ? display : (name + '/' + display);
		}
		var field = showFields[0] , cellData = rowData[field.cellKey];
		var value = (null == cellData.v) ? 0 : Math.floor(cellData.v);
		listData[i] = {name:name,value:value,penetratable: field.penetratable};
	}
	var tableHtml = DataHandler.listCtTableTpl.render({listData:listData});
	t.$dom.find(".list-ct .list-table").html(tableHtml);
	
    //图
	var end = (t.$dom.width() - 30) / (40*chartData.length)*100;
	end = (end < 1) ? 1 : parseInt(end);
	var option = {
			color: defaultColors,
			tooltip: {
				trigger: 'axis',
				triggerOn: 'click',
				axisPointer:{type:'shadow'},
				formatter:function(p){//点击
					var listData = [];
					for(var i = 0, len1 = p.length; i < len1; i++){
						var serie = p[i];
						var fieldKey = serie.seriesName;
						var name = serie.axisValue;
						var value = serie.value;
						var field = DataHandler.getStatsField(t._statsFields_ , fieldKey);
						listData[i] = {fieldKey:fieldKey,itemName :field.display, name:name,value:value,dataIndex:serie.dataIndex,penetratable: field.penetratable};
					}
					var tableHtml = DataHandler.listCtItemsTpl.render({listData:listData,defaultColors:DataHandler.defaultColors});
					t.$dom.find(".list-ct").html(tableHtml);
				},
			},
			xAxis : {
				type : 'category',
				splitLine:{show:true},
				data : xAxisData
			},
			yAxis : {
				type : 'value',
				splitLine:{show:true}
				
			},
			series : series,
			dataZoom:[{
				filterMode:'empty',
	            type: 'inside',
	            start: 0,
	            end: end
	        }],
			grid : {
				containLabel:true,
				x : 10,
				x2 : 10,
				y : 10,
				y2 : 10
			}
		};
	
    var et = echarts.init(t.$dom.find(".chart-ct")[0]);
    et.showLoading({
        text: 'loading...'
    });
    et.hideLoading();
    et.setOption(option,true);
//    //图事件
}
/**
 * 初始化事件
 */
DataHandler.prototype._init_event_ = function(){
	var t = this;
	t.$dom.on("change",".st-ct .op-ct .cross-st",function(){
		t.showContentItems();
	}).on("click",".st-ct .op-ct .show-item-set",function(){
		var $item_ct = t.$dom.find(".st-ct .op-ct .item-ct");
		if($item_ct.hasClass("display_none")){
			$item_ct.removeClass("display_none");
		}else{
			//先重置后隐藏
			t.$dom.find(".st-ct .op-ct .show-items .one-item div").removeClass("actived");
			t.$dom.find(".st-ct .op-ct .show-items .one-item div").addClass("normal");
			var showFields = t._showFields_;
			for(var i = 0, len1 = showFields.length; i < len1; i++){
				var fieldKey = showFields[i].fieldKey;
				var $thisItem = t.$dom.find(".st-ct .op-ct .show-items .one-item[itemKey='"+fieldKey+"'] div");
				$thisItem.removeClass("normal");
				$thisItem.addClass("actived");
		    }
			$item_ct.addClass("display_none");
		}
	}).on("click",".st-ct .op-ct .show-list-all",function(){
		if(t.$dom.find(".list-ct .item-tabs-ct").length == 0){
			var defaultColors = DataHandler.defaultColors;
			var rowHeaders = t._rowHeaders_ , showFields = t._showFields_ , data = t._data_ ;
			//列表
			var listHtml = DataHandler.listCtTpl.render({showFields:showFields,defaultColors:defaultColors});
			t.$dom.find(".list-ct").html(listHtml);
			
			var crossIndex = t.$dom.find(".st-ct .op-ct .cross-st").val() || 0;
			var chartData = data[crossIndex] || [];
			var listData = [];
			for(var i = 0, len1 = chartData.length; i < len1; i++){
				var rowData = chartData[i];
				var name;
				for (var j = 0, len2 = rowHeaders.length; j < len2; j++) {
					var field = rowHeaders[j] , cellData = rowData[field.cellKey];
					var display = (cellData.d == null ) ? "" : cellData.d;
					name = (j == 0) ? display : (name + '/' + display);
				}
				var field = showFields[0] , cellData = rowData[field.cellKey];
				var value = (null == cellData.v) ? 0 : Math.floor(cellData.v);
				listData[i] = {name:name,value:value,penetratable: field.penetratable};
			}
			var tableHtml = DataHandler.listCtTableTpl.render({listData:listData});
			t.$dom.find(".list-ct .list-table").html(tableHtml);
		}
	}).on("click",".st-ct .op-ct .show-items .one-item",function(){
		var len = t.$dom.find(".st-ct .op-ct .show-items .one-item .actived").length;
		var $oneItem = $(this).find("div");
		if($oneItem.hasClass("actived")){//取消统计项
			if(len == 1){
				cmp.dialog.warning(cmp.i18n("report.result.chart.least.one"), function (index) {
		        });
				return;
			}
			$oneItem.removeClass("actived");
			$oneItem.addClass("normal");
		}else{//添加统计项
			if(len == 10){
				cmp.dialog.warning(cmp.i18n("report.result.chart.most.ten"), function (index) {
		        });
				return;
			}
			$oneItem.removeClass("normal");
			$oneItem.addClass("actived");
		}
		
	}).on("click",".st-ct .op-ct .item-bt-reset",function(){//重置
		t.$dom.find(".st-ct .op-ct .show-items .one-item div").removeClass("actived");
		t.$dom.find(".st-ct .op-ct .show-items .one-item div").addClass("normal");
		var showFields = t._showFields_;
		for(var i = 0, len1 = showFields.length; i < len1; i++){
			var fieldKey = showFields[i].fieldKey;
			var $thisItem = t.$dom.find(".st-ct .op-ct .show-items .one-item[itemKey='"+fieldKey+"'] div");
			$thisItem.removeClass("normal");
			$thisItem.addClass("actived");
	    }
	}).on("click",".st-ct .op-ct .item-bt-ok",function(){
		t.$dom.find(".st-ct .op-ct .item-ct").addClass("display_none");
		var items = t.$dom.find(".st-ct .op-ct .show-items .one-item .actived");
		var statsFields = t._statsFields_;
		var showFields = [];
		for(var i = 0, len1 = items.length; i < len1; i++){
			showFields[i] =   DataHandler.getStatsField(statsFields , $(items[i]).parent().attr("itemKey"));
	    }
		t._showFields_ = showFields;
		t.showContentItems();
	}).on("click",".st-ct .list-ct .item-tabs-ct .item-tab",function(){
		t.$dom.find(".st-ct .list-ct .item-tabs-ct .item-tab").removeClass("tab-checked");
		var $oneItem = $(this);
		$oneItem.addClass("tab-checked");
		var itemKey = $oneItem.attr("itemKey");
		
		var rowHeaders = t._rowHeaders_ , statsFields = t._statsFields_, colHeader = t._colHeader_ , data = t._data_, colData = t._colData_ ;
		var showField =  DataHandler.getStatsField(statsFields , itemKey);
		var crossIndex = t.$dom.find(".st-ct .op-ct .cross-st").val() || 0;
		var chartData = data[crossIndex] || [];
		var listData = [];
		for(var i = 0, len1 = chartData.length; i < len1; i++){
			var rowData = chartData[i];
			var name;
			for (var j = 0, len2 = rowHeaders.length; j < len2; j++) {
				var field = rowHeaders[j] , cellData = rowData[field.cellKey];
				var display = (cellData.d == null ) ? "" : cellData.d;
				name = (j == 0) ? display : (name + '/' + display);
			}
			var cellData = rowData[showField.cellKey];
			var value = (null == cellData.v) ? 0 : Math.floor(cellData.v);
			listData[i] = {name:name,value:value,penetratable: showField.penetratable};
		}
		
		var tableHtml = DataHandler.listCtTableTpl.render({listData:listData});
		t.$dom.find(".list-ct .list-table").html(tableHtml);
	}).on("click",".st-ct .list-ct .list-table .penet",function(){
		if(t.options.isPreview){
			return;
		}
		var rowHeaders = t._rowHeaders_ , statsFields = t._statsFields_, colHeader = t._colHeader_ , data = t._data_, colData = t._colData_ ;
		var fieldKey =$(this).attr("itemKey");
		if(fieldKey == undefined || fieldKey == ''){
			fieldKey = t.$dom.find(".list-ct .item-tabs .tab-checked").attr("itemKey");
		}
		var showField =  DataHandler.getStatsField(statsFields , fieldKey);
		if(!showField.penetratable){
			return;
		}
		var dataIndex = $(this).attr("dataIndex");
		var crossIndex = t.$dom.find(".st-ct .op-ct .cross-st").val() || 0;
		var chartData = data[crossIndex] || [];
	    var rowData = chartData[dataIndex];
	    
		var titleName = '' , values = {} ;
		for(var k = 0, len3 = rowHeaders.length; k < len3; k++){
			var hField = rowHeaders[k];
			var cellData = rowData[hField.cellKey];
			var display = (cellData.d == null ) ? "" : cellData.d;
			titleName = titleName + display + '_';
			values[hField.fieldKey]= cellData.v;
		}
		if(null != colHeader){//有交叉项
			var cellData = colData[crossIndex];
			var display = (cellData.d == null ) ? "" : cellData.d;
			titleName = titleName + display + '_';
			values[colHeader.fieldKey]= cellData.v;
		}
		
		titleName += showField.display;
		titleName += '(';
		if (showField.calcType == 'count') {
			titleName += cmp.i18n("report.result.common.count");//cmp.i18n("report.common.nodata")
		} else if (showField.calcType == 'sum') {
			titleName += cmp.i18n("report.result.common.sum");
		} else if (showField.calcType == 'avg') {
			titleName += cmp.i18n("report.result.common.avg");
		} else if (showField.calcType == 'max') {
			titleName += cmp.i18n("report.result.common.max");
		} else if (showField.calcType == 'min') {
			titleName += cmp.i18n("report.result.common.min");
		} else if (showField.calcType == 'earliest') {
			titleName += cmp.i18n("report.result.common.earliest");
		} else if (showField.calcType == 'latest') {
			titleName += cmp.i18n("report.result.common.latest");
		}
		titleName += ')';
		var titleValue = rowData[showField.cellKey].v;
		titleValue = (null == titleValue) ? 0 : titleValue;
		
		rptApi.getStatsPenetrateInfo({},{designId:t.options.designId},{
			success:function(rs){
				if(rs.penetrateMode == 'query'){
					RptUtils.load_jscss([vreportPath + "/vreport_m_api.s3js"],[],function(){
						var toDesignId = rs.designId ,headFieldMaps = rs.headFieldMaps , filterFieldMaps = rs.filterFieldMaps;
						var filterValue = RptUtils.getFilterValue(values,t.options.userConditions,headFieldMaps,filterFieldMaps);
						vreportApi.reportView({rptInfo:{module:'4',relatedId:toDesignId,filterValue:filterValue}});
					});
				}else{
					var params = {titleName:titleName,titleValue:titleValue,
							designId:t.options.designId,
							statsField:showField.fieldKey,
							userConditions:t.options.userConditions,
							fieldValues:values
					};
					cmp.href.next(vreportPath + "/html/defaultPenetList.html",params);
				}
				cmp.dialog.loading(false);
			},
			error:function(error){
				cmp.dialog.loading(false);
				var cmpHandled = cmp.errorHandler(error);
				if (!cmpHandled) {
					if (error.message) {
						DataHandler.alert(error.message);
					} else {
						DataHandler.alert(cmp.toJSON(error));
					}
				}
			}
		});
	});
}

/**
 * 查找统计项
 */
DataHandler.getStatsField = function(statsFields , fieldKey){
	for(var i = 0, len1 = statsFields.length; i < len1; i++){
		if(fieldKey == statsFields[i].fieldKey){
			return statsFields[i];
		}
	}
	return ;
}
DataHandler.alert = function(tips){
	cmp.notification.alert(tips);
}

DataHandler.showChartTpl = laytpl('\
	<div class="st-ct">\
		<div class="op-ct">\
			<div class="cross-set"></div>\
			<div class="item-set">\
				<div class="show-list-all">\
					<i class="see-icon-v5-common-bulletin"></i>\
					<span>{{d.labelAll }}</span>\
				</div>\
				<div class="show-item-set">\
				    <i class="see-icon-v5-common-bulletin"></i>\
				    <span>{{d.labelItems }}</span>\
				</div>\
			</div>\
			<div class="item-ct display_none">\
				<div class="show-items"></div>\
				<div class="btnList">\
					<button type="button" class="cmp-btn item-bt-reset">{{d.labelReset }}</button>\
					<button type="button" class="cmp-btn cmp-btn-primary item-bt-ok">{{d.labelOk }}</button>\
				</div>\
			</div>\
		</div>\
		<div>\
			<div class="chart-ct"></div>\
		</div>\
		<div class="list-ct"></div>\
	</div>');
DataHandler.statsItemsTpl = laytpl('\
	{{#\
		for(var i=0;i<d.statsFields.length;i++){\
				var fieldKey = d.statsFields[i].fieldKey;\
	}}\
		<div itemKey="{{fieldKey }}" class="one-item">\
	        <div class="{{# if(i < 10){ }}actived{{# }else{ }}normal{{# } }}">{{=d.statsFields[i].display}}</div>\
	    </div>\
	{{#\
		}\
	}}');


DataHandler.opCrossTpl = laytpl('\
	{{# if(d.colData.length == 1){ }}\
		<div class="op-ct-label"><lable>{{=d.colData[0].d }}</lable></div>\
	{{# }else{ }}\
		<select class="cross-st">\
			{{#\
				for(var i=0;i<d.colData.length;i++){\
			}}\
				<option value="{{i }}">{{=d.colData[i].d }}</option>\
			{{#\
				}\
			}}\
		</select>\
	{{# } }}');
DataHandler.listCtTpl = laytpl('\
	<div class="title-row">\
		<div class="item-tabs-ct">\
		    <div class="item-tabs" style="width:{{100*(d.showFields.length + 1)}}px;">\
			{{#\
				for(var i=0;i<d.showFields.length;i++){\
					var fieldKey = d.showFields[i].fieldKey;\
					var colorSize = i % d.defaultColors.length;\
			}}\
				<div itemKey="{{fieldKey }}" class="item-tab {{# if(i == 0){ }}tab-checked{{# } }}">\
			        <div class="item-color" style="background-color:{{d.defaultColors[colorSize] }};"></div>\
			        <span>{{=d.showFields[i].display }}</span>\
			    </div>\
			{{#\
				}\
			}}\
		    </div>\
		</div>\
	</div>\
	<div class="list-table">\
	</div>');

DataHandler.listCtTableTpl = laytpl('\
	{{# var  wd = window.innerWidth, nameWd = wd - 140; }}\
	<table class="" border="0" cellspacing="0" cellpadding="0">\
        <tbody>\
			{{# for(var i = 0, len1 = d.listData.length; i < len1; i++){ \
				var penetratable = d.listData[i].penetratable;\
			}}\
			<tr dataIndex="{{i }}" class="{{# if(penetratable){ }}penet{{# } }}">\
		        <td class="row-n">\
		            <div class="row-name" style="width:{{nameWd }}px">{{=d.listData[i].name }}</div>\
		        </td>\
		        <td class="row-v">\
		            <div class="row-value">{{Math.floor(d.listData[i].value) }}</div>\
		        </td>\
				<td class="row-i">{{# if(penetratable){ }}<i class="cmp-icon cmp-icon-arrowright"></i>{{# } }}</td>\
		    </tr>\
			{{# } }}\
        </tbody>\
    </table>');
DataHandler.listCtItemsTpl = laytpl('\
	{{# var  wd = window.innerWidth, nameWd = wd - 160; }}\
	<div class="list-table">\
		<table class="" border="0" cellspacing="0" cellpadding="0">\
	        <tbody>\
				{{# for(var i = 0, len1 = d.listData.length; i < len1; i++){ \
					var size = i % d.defaultColors.length ;\
					var penetratable = d.listData[i].penetratable;\
				}}\
	            <tr dataIndex="{{d.listData[i].dataIndex }}" itemKey="{{d.listData[i].fieldKey }}" class="{{# if(penetratable){ }}penet{{# } }}">\
					<td class="row-c">\
				        <div class="row-color">\
				            <div style="background-color:{{d.defaultColors[size] }};"></div>\
				        </div>\
				    </td>\
					<td class="row-n">\
	                    <div class="row-name2" style="width:{{nameWd }}px">{{=d.listData[i].itemName }}</div>\
						<div class="row-name2" style="width:{{nameWd }}px">{{=d.listData[i].name }}</div>\
	                </td>\
	                <td class="row-v">\
	                    <div class="row-value">{{Math.floor(d.listData[i].value) }}</div>\
	                </td>\
					<td class="row-i">{{# if(penetratable){ }}<i class="cmp-icon cmp-icon-arrowright"></i>{{# } }}</td>\
	            </tr>\
				{{# } }}\
	        </tbody>\
	    </table>\
	</div>');
DataHandler.defaultColors = ["#67bfff", "#20cf6d", "#f3b700", "#ec4c35", "#9d56ba", "#6799ff", "#19c170", "#f3ce00", "#ec6035", "#a63eb9", "#3664e6", "#a0cf20", "#f3e500", "#ec8335", "#b928c2", "#173dce", "#7fcf20", "#ebf300", "#f39500", "#C22883"];


